import { Component, Vue } from 'vue-property-decorator'
import axios from '@axios/user'

@Component
export class RegisterBox extends Vue {

    /** 邮箱 */
    private email: string = '';

    /** 验证码 */
    private token: string = '';

    /** 密码 */
    private passwd: string = '';

    /** 再次确认密码 */
    private passwd2: string = '';

    /** 阅读服务条款 */
    private single: Boolean = false;

    /** 存储邮箱出现的问题 */
    private emailCheck: Array<string> = [];

    /** 存储密码出现的问题 */
    private passwdCheck: Array<string> = [];

    /** 存储再次确认密码出现的问题 */
    private passwd2Check: Array<string> = [];

    /** 存储验证码的问题 */
    private tokenCheck: Array<string> = [];

    /** 验证码倒计时 */
    private tokenCount: number = 0;

    
    /**
     * 在电子邮箱文本框失去焦点时被调用, 
     * 检查电子邮箱是否正确,
     * 不正确的信息将被记入 emailCheck
     */
    public checkEmail(): void {
        this.emailCheck = [];
        if (!this.email.isEmail()) {
            this.emailCheck.push('请输入正确的邮件地址');
        }
    }

    /**
     * 检查验证码是否正确
     */
    public checkToken(): void {
        this.tokenCheck = [];
        if (this.token.length > 6 || isNaN(parseInt(this.token))) {
            this.tokenCheck.push('请输入正确的验证码形式');
        }
    }

    /**
     * 在密码文本框失去焦点时被调用,
     * 检查密码是否正确,
     * 不正确的信息将被记入 passwdCheck
     */
    public checkPasswd(): void {
        this.passwdCheck = [];
        if (this.passwd.length < 8) {
            this.passwdCheck.push('至少包含8个字符');
        }
        if (this.passwd.isPassword()) {
            this.passwdCheck.push('必须包含大小写字母和数字的组合');
        }
    }

    /**
     * 在再次确认密码文本框失去焦点时被调用,
     * 检查再次确认密码是否正确,
     * 不正确的信息将被记入 passwd2Check
     */
    public checkPasswd2(): void {
        this.passwd2Check = [];
        if (this.passwd2 != this.passwd) {
            this.passwd2Check.push("两次输入的密码不一致");
        }
    }

    /**
     * 判断是否能注册
     * 需要密码框、密码框、再次确认密码框里面都没有错误提示, 并且已阅读服务条框
     */
    public canRegister(): boolean {
        return  this.emailCheck.length != 0 ||
                this.passwdCheck.length != 0 ||
                this.passwd2Check.length != 0 || 
                this.tokenCheck.length != 0 ||
                this.single == false;
    }

    /**
     * 注册
     */
    private doRegister(): void {
        axios.base.register({
            email: this.email.encrypt(),
            password: this.passwd.encrypt(),
            token: this.token
        }).then(res => {
            if (res) {
                this.$emit('on-click');
            }
        });
    }

    private getToken(): void {
        if (this.email.isEmpty() || this.emailCheck.length > 0) {
            "请先完成邮箱填写".notifyWarn();
            return;
        }
        axios.base.getToken(this.email);
        this.tokenCount = 60;
        let that = this;
        let timer = setInterval(() => {
            that.tokenCount--;
            if (that.tokenCount == 0) {
                clearInterval(timer);
            }
        }, 1000);
    }

}